package com.controller;

import com.util.AliOSSUtils;
import com.util.OSSFile;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;

import static com.util.Vessel.hashValue;


@Controller
public class FileController {

    @Resource
    private OSSFile oSSFile;

    @Resource
    private AliOSSUtils aliOSSUtils;

    @RequestMapping
    public String uploads(){
        return "/uploads";
    }

    /**
     * 文件上传方法
     *
     * @param file 上传的文件
     * @return 返回上传结果
     */
    @RequestMapping("/upload")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        try {
            // 调用工具类上传文件到OSS
            String upload = aliOSSUtils.upload(file);//shading  upload
            System.out.println("上传成功: " + upload);
            return ResponseEntity.ok("上传成功: " + upload);
        } catch (Exception e) {
            // 处理上传失败的情况
            e.printStackTrace();
            System.out.println("上传失败: " + e.getMessage());
            return ResponseEntity.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
                    .body("上传失败: " + e.getMessage());
        }
    }

    @RequestMapping("/BigFileUpload")
    public ResponseEntity<String> BigFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            // 调用工具类上传文件到OSS
            String upload = aliOSSUtils.shading(file);//shading  upload
            System.out.println("上传成功: " + upload);
            return ResponseEntity.ok("上传成功: " + upload);
        } catch (Exception e) {
            // 处理上传失败的情况
            e.printStackTrace();
            System.out.println("上传失败: " + e.getMessage());
            return ResponseEntity.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
                    .body("上传失败: " + e.getMessage());
        }
    }

    /**
     * 文件下载方法
     *
     * @param filename 要下载的文件名
     * @return 返回下载结果
     */
    @RequestMapping("/downloads")
    @ResponseBody
    public String downloads(@RequestParam("filename") String filename,@RequestParam("saveName") String saveName) {
        // 使用 try-with-resources 自动管理资源
        try (InputStream inputStream = aliOSSUtils.downloads(oSSFile.getBucketName(), filename);
             BufferedInputStream in = new BufferedInputStream(inputStream)) {

            // 将下载的文件保存到指定路径
            Path filePath = Paths.get("C:\\Users\\Taylor\\Downloads", saveName + ".png");
            try (OutputStream outputStream = Files.newOutputStream(filePath);
                 BufferedOutputStream out = new BufferedOutputStream(outputStream)) {

                byte[] buffer = new byte[1500];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
            }

            // 读取保存的文件内容为字节数组
            byte[] fileContent = Files.readAllBytes(filePath);
            String hashValues = aliOSSUtils.getHashValues(new ByteArrayInputStream(fileContent));
            if (hashValue!=null&&hashValue.equals(hashValues)){
                System.out.println("数据完整校验成功");
                String encodedFilename = URLEncoder.encode(filename + ".png", "UTF-8");
                // 设置响应头，指示浏览器下载文件
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment", encodedFilename);
                System.out.println("下载成功: " + filePath.toString());
            }else {
                System.out.println("数据完整校验失败");
            }

            return "下载成功" + filePath.toString();
        } catch (Exception e) {
            // 处理下载失败的情况
            e.printStackTrace();
            System.out.println("下载失败: " + e.getMessage());
            return "下载失败: " + e.getMessage();
        }
    }
}